package official_account

import (
	"code.gitea.io/gitea/modules/log"
	"code.gitea.io/gitea/modules/setting"
	Result "code.gitea.io/gitea/routers/entity"
	gitea_web_context "code.gitea.io/gitea/services/context"
	wechat_official_account_service "code.gitea.io/gitea/services/wechat/official_account"
)

// GenerateWechatOfficialAccountQrCode 生成微信公众号临时带参数二维码
//
//	GET /api/wechat/official-account/login/qr/generate?qrExpireSeconds=${qrExpireSeconds}&sceneStr=${sceneStr}
func GenerateWechatOfficialAccountQrCode(ctx *gitea_web_context.APIContext) {

	// 1. 检查微信功能是否启用
	if setting.Wechat.OfficialAccount.PowerWechat == nil {
		errorMsg := "微信公众号功能禁用, 不会生成公众号带参数二维码"
		log.Warn(errorMsg)
		respFailed := Result.ResultType{
			Code: Result.RespFailedWechatMalconfigured.Code,
			Msg:  Result.RespFailedWechatMalconfigured.Msg,
			Data: map[string]string{
				"ErrorMsg": errorMsg,
			},
		}
		respFailed.RespondJson2HttpResponseWriter(ctx.Resp)
		return
	}

	// 2. 解析 HTTP GET 请求参数，调用 service 层生成二维码
	qrExpireSeconds := ctx.FormInt("qrExpireSeconds")
	sceneStr := ctx.FormString("sceneStr")
	qrCodeVO, err := wechat_official_account_service.GenerateTempQR(ctx, sceneStr, qrExpireSeconds)
	if err != nil {
		respFailed := Result.ResultType{
			Code: Result.RespFailedGenerateWechatOfficialAccountTempQR.Code,
			Msg:  Result.RespFailedGenerateWechatOfficialAccountTempQR.Msg,
			Data: map[string]string{
				"ErrorMsg": err.Error(),
			},
		}
		respFailed.RespondJson2HttpResponseWriter(ctx.Resp)
		return
	}

	// 3. 返回 (自动对VO对象进行JSON序列化)
	repsSuccessGenerateQRCode := Result.ResultType{
		Code: Result.RespSuccess.Code,
		Msg:  Result.RespSuccess.Msg,
		Data: qrCodeVO,
	}
	repsSuccessGenerateQRCode.RespondJson2HttpResponseWriter(ctx.Resp)
	return
}
